package cn.itcast.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGloabalFilter implements GlobalFilter, Ordered {

    /**
     * 需求 ：请求参数中带有token 内容，就放行，否则提示未授权
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("自定义全局过滤器....");
       //获取Request请求
        ServerHttpRequest request = exchange.getRequest();
        //获取response响应
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getQueryParams().getFirst("token");
        //判断请求有没有带token参数，如果没有，返回403状态码
         if (StringUtils.isNotEmpty(token)){
             //token不为空，进入微服务，放行
             return chain.filter(exchange);//直接放行
         }else {
             //token为空
             // 设置状态码
             response.setStatusCode(HttpStatus.FORBIDDEN);
             return response.setComplete();//直接返回给浏览器
         }
    }

    /**
     * 返回的值越小，当前过滤器越优先执行，一般不用指定
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
